<?php

namespace app\common\service\store;

use app\admin\model\store\GoodsCoupon;
use app\admin\model\store\GoodsCouponContact;
use app\admin\model\store\GoodsCouponIssueUser;
use app\common\service\BaseService;
use app\common\service\coupon\CouponContext;
use app\common\service\coupon\MJCouponDiscount;
use app\common\service\coupon\ZJCouponDiscount;
use app\common\service\coupon\ZKCouponDiscount;
use app\common\service\user\UserAttentionService;
use think\facade\Cache;

class GoodsCouponService extends BaseService
{
    /**
     * Author:Zhongyuan Lu
     * 后台添加优惠券
     * @param $params
     * @return array
     */
    public static function createCoupon($params)
    {
        $goods_ids = [];

        //商品券
        if ($params['type'] == 1) {
            if (empty($params['goods_id'])) {
                return self::fail('商品券对应添加商品id为空');
            }
            $goods_ids = explode(',', $params['goods_id']);
        }

        //开始时间必须小于结束时间
        if ($params['end_time'] < $params['start_time']) {
            list($params['start_time'],$params['end_time']) = [$params['end_time'],$params['start_time']];
        }

        //优惠券剩余数量必须小于等于优惠券总量
        if ($params['remain_count'] > $params['total_count'] || empty($params['remain_count'])) {
            $params['remain_count'] = $params['total_count'];
        }

        $id = GoodsCoupon::create($params)->id;
        if ($id) {
            if ($params['type'] == 1) {
                foreach ($goods_ids as $k => $v) {
                    $goodsCouponContact[$k]['coupon_id'] = $id;
                    $goodsCouponContact[$k]['goods_id'] = $v;
                }
                GoodsCouponContactService::saveAll($goodsCouponContact);
            }
            return self::success('添加成功');
        }
        return self::fail('添加失败');
    }

    /**
     * Author:Zhongyuan Lu
     * 前台获取优惠券
     * @param $couponId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGoodsCoupon($type, $couponId = [], $uid = 17)
    {
        //状态为正常的商品券
        $where = [
            ['status', '=', 1],
            ['type', '=', $type]
        ];
        $field = ['id', 'title', 'image', 'start_time', 'end_time', 'is_give_subscribe', 'coupon_price'];
        $mode = new GoodsCoupon();
        if ($type == 1) {
            $mode->whereIn('id', $couponId);
        }
        $data = $mode->where($where)->field($field)->select();
        $data && $data = $data->toArray();
        if (!empty($data)) {
            //判断是否领取过
            foreach ($data as &$v) {
                $where = [
                    ['uid', '=', $uid],
                    ['coupon_id', '=', $v['id']]
                ];
                $res = GoodsCouponIssueUser::where($where)->find();
                $v['is_use'] = !empty($res) ? 1 : 0;
                $v['start_time'] = date('Y.m.d', $v['start_time']);
                $v['end_time'] = date('Y.m.d', $v['end_time']);
            }
            unset($v);
            return self::success('success', $data);
        }
        return self::fail('fail');
    }

    /**
     * Author:Zhongyuan Lu
     * 获取商品券对应的优惠券ID
     * @param int $type
     * @param int $goods_id
     * @return array
     */
    public static function getGoodsCouponId($goods_id = 0)
    {
        $where = [];
        if (is_int($goods_id)) {
            $where = ['goods_id', '=', $goods_id];
        }
        if (is_array($goods_id)) {
            $where = ['goods_id', 'in', $goods_id];
        }
        $data = GoodsCouponContact::where($where)->column('coupon_id');
        if (!empty($data)) {
            return self::success('success', $data);
        }
        return self::fail('fail', $data);
    }

    /**
     * Author:Zhongyuan Lu
     * 领取优惠券
     * @param $uid
     * @param $couponId
     * @param $goods_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function collectCoupon($uid, $couponId, $goods_id)
    {
        //判断是否领取过此优惠券
        $data = GoodsCouponIssueUser::where('uid', $uid)->where('coupon_id', $couponId)->find();
        $data && $data = $data->toArray();
        if (!empty($data)) {
            return self::fail('已领取过此优惠券');
        }
        //需要查询的列
        $field = [
            'coupon_time',  //优惠券有效期
            'remain_count', //优惠券剩余领取数量
            'is_permanent', //是否无限张(0：否 1：是)
            'is_give_subscribe',    //是否首次关注赠送 （0：否 1：是）
            'coupon_time',    //优惠券过期时间
        ];
        $where = [
            ['status', '=', 1],
            ['start_time', '<', time()],
            ['end_time', '>', time()],
        ];
        $goodsCoupon = GoodsCoupon::where($where)->field($field)->find($couponId);
        $goodsCoupon && $goodsCoupon = $goodsCoupon->toArray();
        if (empty($goodsCoupon)) {
            return self::fail('优惠券已失效');
        }
        //如果不是无限张，那么剩余领取数量应该不能小于等于0
        if (!$goodsCoupon['is_permanent'] && $goodsCoupon['remain_count'] <= 0) {
            return self::fail('优惠券已领完');
        }

        //如果是首次关注赠送  查询关注次数
        if ($goodsCoupon['is_give_subscribe']) {
            $res = UserAttentionService::isFirstAttention($uid, $goods_id);
            if ($res['code'] == 400) {
                return $res;
            }
        }

        $ret = [
            'uid' => $uid,
            'coupon_id' => $couponId,
            'invalid_time' => strtotime("+{$goodsCoupon['coupon_time']} days"),
        ];

        self::beginTrans();
        try {
            //创建用户领取记录 并 修改优惠券剩余领取数量
            GoodsCouponIssueUser::create($ret);
            if (!$goodsCoupon['is_permanent'] && $goodsCoupon['remain_count'] == 1) {
                $data = [
                    'remain_count' => $goodsCoupon['remain_count'] - 1,
                    'status' => -1,
                ];
            } else {
                $data = ['remain_count' => $goodsCoupon['remain_count'] - 1];
            }
            GoodsCoupon::where('id', $couponId)->update($data);
            self::commitTrans();
            return self::success('领取成功');
        } catch (\Exception $e) {
            self::rollbackTrans();
            self::fail('领取失败');
        }
    }

    /**
     * Author:YangXinPeng
     * 使用优惠券
     * @param $coupon
     * @param $price
     * @return array
     */
    public static function useCoupon($couponId, $price ,$uid)
    {
        $coupon = GoodsCoupon::find($couponId);
        $coupon && $coupon = $coupon->toArray();
        $where['uid'] = $uid;
        $where['coupon_id'] = $couponId;
        GoodsCouponIssueUser::where($where)->update(['status'=>1]);
        switch ($coupon['discount_method']) {
            case "满减":
                $money = self::useMJCoupon($coupon, $price);
                return $money;
                break;
            case "直减":
                $money = self::useZJCoupon($coupon, $price);
                return $money;
                break;
            case "折扣":
                $money = self::useZKCoupon($coupon, $price);
                return $money;
                break;
        }
    }

    /**
     * Author:YangXinPeng
     * @param $coupon
     * @param $price
     * @return mixed
     */
    public static function useZJCoupon($coupon, $price)
    {
        $context = new CouponContext(new ZJCouponDiscount());
        $money = $context->prefere($coupon, $price);
        return $money;
    }

    /**
     * Author:YangXinPeng
     * @param $coupon
     * @param $price
     * @return mixed
     */
    public static function useZKCoupon($coupon, $price)
    {
        $context = new CouponContext(new ZKCouponDiscount());
        $money = $context->prefere($coupon, $price);
        return $money;
    }

    /**
     * Author:YangXinPeng
     * @param $coupon
     * @param $price
     * @return mixed
     */
    public static function useMJCoupon($coupon, $price)
    {
        $context = new CouponContext(new MJCouponDiscount());
        $money = $context->prefere($coupon, $price);
        return $money;
    }


}